<?php



namespace api\modules\v1\controllers;
use yii\rest\Controller;
use yii\helpers\ArrayHelper;
use Yii;
use backend\module\content\models\ContentCategory;
use yii\data\Pagination;
use yii\widgets\LinkPager;
/**
 * Description of ContentController
 *
 * @author zhuo bing
 */
class ContentsController extends BaseController{

    public function actionIndex(){
        $request = Yii::$app->request;
        $cid = intval($request->get('cid',0));
        $catInfo = ContentCategory::findOne($cid);
        
        $regionId  = intval($request->get('region_id',0));
        $lat = (float) $request->get('lat');
        $lng =  (float)$request->get('lng');
        
        $params = [':cid'=>$cid,':region_id'=>$regionId,':lat'=>$lat,':lng'=>$lng];
        
        $page = $request->get('page',1);
        $page = $page-1;
        
        
        $sql = "select count(id),ROUND(6378.138*2*ASIN(SQRT(POW(SIN((:lat*PI()/180-map_lat*PI()/180)/2),2)"
                . "+COS(:lat*PI()/180)*COS(map_lat*PI()/180)*POW(SIN((:lng*PI()/180-map_lng*PI()/180)/2),2)))*1000) AS distance"
                . " from sshop_{$catInfo['controller']} where region_id = :region_id and catid = :cid order by distance";
        $data = Yii::$app->db->createCommand($sql)
            ->bindValues($params)
            ->queryOne();
        $count = count($data['count(id)']);
        
        $pagination = new Pagination(['totalCount' => $count,'page'=>$page]);
        
        $sql = "select id,ROUND(6378.138*2*ASIN(SQRT(POW(SIN((:lat*PI()/180-map_lat*PI()/180)/2),2)"
                . "+COS(:lat*PI()/180)*COS(map_lat*PI()/180)*POW(SIN((:lng*PI()/180-map_lng*PI()/180)/2),2)))*1000) AS distance"
                . " from sshop_{$catInfo['controller']} where region_id = :region_id and catid = :cid order by distance limit ".$pagination->offset.','.$pagination->limit;
        $data = Yii::$app->db->createCommand($sql)
            ->bindValues($params)
            ->queryAll();        
        return $data;
    }

}
